/**
 * @Author: wangliuyang
 * @Date: 2021/9/7 21:10
 * @Description:116. 填充每个节点的下一个右侧节点指针
 */
public class Solution_116 {
    public Node connect(Node root) {
        if (root == null){
            return null;
        }
        /**
         * 总体上先从上往下遍历,每一层从左到右,在第当前层填好下一层信息.
         */
        Node mostLeft  = root;
        while (mostLeft.left != null){
            Node head = mostLeft;
            while (head != null){
                head.left.next = head.right;
                if (head.next != null){
                    head.right.next = head.next.left;
                }
                head = head.next;
            }
            mostLeft = mostLeft.left;
        }
        return root;
    }
}

class Node {
    public int val;
    public Node left;
    public Node right;
    public Node next;

    public Node() {}

    public Node(int _val) {
        val = _val;
    }

    public Node(int _val, Node _left, Node _right, Node _next) {
        val = _val;
        left = _left;
        right = _right;
        next = _next;
    }
};
